package com.compuvest.web;

// <editor-fold defaultstate="collapsed" desc="import">
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
// </editor-fold>

public class Preferences implements java.io.Serializable {

    private String title;
    private int index;
    private Map<String,Counter> contents;

// <editor-fold defaultstate="collapsed" desc="Preferences()">

    public Preferences() {
        this(0);
    }

    public Preferences(int index) {
        this.index = index;
        contents = new HashMap<>();
    }
// </editor-fold>

    public String getTitle()            { return title; }
    public void  setTitle(String title) { this.title = title; }

// <editor-fold defaultstate="collapsed" desc="add()">

    public void add(String word) {

        if(contents.containsKey(word)) {
            contents.get(word).count++;
        }
        else {
            contents.put(word, new Counter());
        }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="haveData()">

    public boolean haveData() {
        return title.length() != 0 && !contents.isEmpty();
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="toString()">

    @Override
    public String toString() {

        StringBuilder result = new StringBuilder();

        if(!contents.isEmpty()) {
            result.append("{nm:'").append(title).append("',pl:[");
            Iterator iter = contents.keySet().iterator();
            String pref;
            for(int idx = 0; iter.hasNext(); idx++) {
                pref = (String)iter.next();
		if(idx != 0) result.append(',');
                result.append("{id:").append(index).append(",nm:'").append(pref).append("',cn:").append(contents.get(pref)).append("}");
            }
            result.append("]}");
        }

        return result.toString();

    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="class Counter">

    class Counter {
        int count = 1;

        @Override
        public String toString() {
            return Integer.toString(count);
        }
    }
// </editor-fold>

}
